var colonyBlue = require("../../../pages/index/colony_blue.js")
var ConstantData = require('../../../common/constant_data.js')
var BLELocker = require('../../../common/BLELocker.js')
var connectUtil = require('../../../utils/ble-dfu/connect.js');
var common = require("../../../common/common.js")
var commonUtil = require('../../../utils/commonUtil');
var statistic = require("../../../pages/index/statistic.js")
var util = require('../../../utils/util.js');
var noDepositLease = require("../../../pages/index/no_deposit_lease.js")

var app = getApp()
var connectShow = null
var leaseShow = null
var bleAuthShow = null
var bleFailShow = null

function connectBox(that) {
  if (app.globalData.timeoutConnectTimeout) {
    clearTimeout(app.globalData.timeoutConnectTimeout)
  }
  that.data.firstConStat = true
  connectShow = that.data.connectShow
  leaseShow = that.data.leaseShow
  bleAuthShow = that.data.bleAuthShow
  bleFailShow = that.data.bleFailShow
  that.handleStatus = (status, data) => {
    handleStatus(status, data)
  }
  app.globalData.devConnected = false

  connectShow.reday()
  that.data.conMac = that.data.mac;
  //网关连接
  if (that.data.isColonyCon) {
    console.log("网关连接---->", that.data.mac);
    that.data.connectShow.networkConnecting()
    that.startGatewayConnect = () => {
      colonyBlue.connectDev(that.data.mac, that);
    }
    //断开完成后 发起网关标记
    that.data.disCompleteConFlg = true
    colonyBlue.gatewayDisCon(that, 'newConUtil22')
  } else {
    console.log("蓝牙直连---->", that.data.curBlueName);
    let blueName = that.data.curBlueName
    connectBLEDevice(blueName, that)
  }
}

//连接蓝牙设备
function connectBLEDevice(blueName, that) {
  that = !that ? app.globalData.newConThat : that
  var systemInfo = that.data.systemInfo
  let platform = systemInfo.platform.toLowerCase()
  app.globalData.platform = platform
  let isCheckLocation = false
  //是否是安卓系统
  if (platform == 'android') {
    //安卓系统采取直连，兼容之前版本
    that.data.curIsDirectCon = true
    //检查是否标记不能使用直连方式
    let directConForbidden = wx.getStorageSync('direct_con_forbidden')
    let directConSuc = wx.getStorageSync('direct_con_suc')
    console.warn('是否直标记连判断', directConSuc, directConForbidden)
    if (!directConSuc && directConForbidden == 1) {
      //禁止直连
      that.data.curIsDirectCon = false
      isCheckLocation = true
    }
  }

  let isGatewayConFlg = colonyBlue.isGatewayCon(that);
  if (isGatewayConFlg) {
    //是否蓝牙方式连接
    that.data.curContIsBle = false
    console.log("开始网关连接", blueName)
    that.setData({
      loading_show: true,
      loading_desc: '网关连接准备中...',
      connectDesc: "网关连接准备中...",
    });
    colonyBlue.connectDev(blueName.replace("DK", ""), that);
    return;
  } else {
    that.data.curContIsBle = true
    if (isCheckLocation) {
      //校验位置权限
      let authRst = commonUtil.validateOnlyLocationAuth()
      if (authRst == 'sys_location') {
        //跳转到系统定位权限        
        if (systemInfo.platform == 'ios') {
          //苹果系统
          bleAuthShow.showIosSysLocationSetting()
        } else {
          bleAuthShow.showAndroidSysLocationSetting()
        }
        return
      } else if (authRst == 'wx_location') {
        bleAuthShow.showAppLocationSetting()
        return
      }
    }
  }

  common.storeWxClientType(that);

  console.log("connecting...." + blueName)
  that.data.canceledConnect = false;

  //连接开始准备
  connectShow.start();
  that.data.mac = blueName.replace("DK", "")
  that.data.startConTime = new Date().getTime()

  BLELocker.setErrorCallback(function (errType, errDesc) {
    that.recordBlueConnectError(errType, errDesc)
  })
  BLELocker.setConnectLogCall(function (data) {})

  //关闭心跳定时器
  if (that.data.bleHeartTimer) {
    clearInterval(that.data.bleHeartTimer);
    console.log("连接前关闭之前的心跳定时器");
  }
  app.globalData.conIsSuc = false;
  app.globalData.upgradeMac = blueName;
  app.globalData.startConTime = new Date().getTime();
  //是否开锁中
  app.globalData.isOpenLock = false;
  app.globalData.isUpgradeing = false;

  //连接中标记
  app.globalData.isConnecting = true;
  //当前连接的mac
  that.data.mac = blueName.replace('DK', '');
  //连接前清空上一次扫码的设备记录
  BLELocker.setDevice(null);
  that.data.blueName = blueName;
  //是否搜的onBluetoothDeviceFound响应超时
  app.globalData.isFindTimeout = false;

  app.globalData.isDirectConnect = false;
  clearInterval(app.globalData.directConnectTimer)

  if (that.data.curIsDirectCon) {
    console.warn("蓝牙直连-----》")
    app.globalData.isDirectConnect = true;
    app.globalData.newConThat.data.openBlueAdapterFail = false;
    app.globalData.isLeaseCon = true;
    that.recordBlueConnectError(ConstantData.err_type.connect_direct_start, 'direct connect start');
    BLELocker.setParams(function (status, data) {
      handleStatus(status, data)
    }, that);
    connectUtil.directBleCon(blueName, that.data.wxDeviceId)
  } else {
    console.log("使用新连接进行连接");
    //非直接连接
    app.globalData.isDirectConnect = false;
    app.globalData.newConThat.data.openBlueAdapterFail = false;
    app.globalData.isLeaseCon = true;
    BLELocker.setParams(function (status, data) {
      handleStatus(status, data)
    }, that);
    connectUtil.startCon(blueName);
    let isWxScan = that.data.isWxScanFlg ? "wxScan" : "ejiaScan";
    if (that.data.canRetry85) {
      isWxScan = isWxScan + ':retry85Con';
    }
    that.recordBlueConnectError(ConstantData.err_type.new_con, 'new connect 1.0 start:' + isWxScan);
  }

}

//处理设备连接状态变化回调
var handleStatus = (status, data) => {
  var that = app.globalData.newConThat
  console.log('我就是_Callback', status, data)
  let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
  if (status == BLELocker.Status.ble01Data) {
    console.log("---新固件驱动连接成功...", data);
    //连接成功数据读取中
    connectShow.read();
    //新固件会主动上报95数据
  } else if (status == BLELocker.Status.bleScanStart) {
    connectShow.discover()
  } else if (status == BLELocker.Status.appVersionNotSupported) {
    getApp().hideLoading()

    //1.关闭正在连接的提示对话框 2.弹出提示用户APP版本太低不支持的对话框
    leaseShow.resultShow("微信APP版本太低不支持")

  } else if (status == BLELocker.Status.bleIsClosed) {
    getApp().hideLoading()
    let systemInfo = wx.getStorageSync('systeminfo');
    if (systemInfo.system && systemInfo.system.toLowerCase().indexOf('ios 13') != -1) {
      bleFailShow.modalMsgShow()
      that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          icon_name: 'icon-lanya',
          desc: '请在系统设置中打开微信的蓝牙权限后重试',
          desc_center: true,
          desc_mini: 'BT权限不成功' + pile_id + '(' + that.data.phoneInfo + '-100310)',
          open_ble_auth_show: true,
        }
      })
      that.recordBlueConnectError(100310, "modalErr:ios13-蓝牙未打开");
    } else {
      bleFailShow.modalMsgShow()
      that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: 'BT未打开' + pile_id + '（' + that.data.phoneInfo + '-100311)',
          desc: '请打开蓝牙后重试', //此处的文字在wxml页面有用到，如果变更的话wxml也要同步变更
          retryConnect: true
        }
      })
      that.recordBlueConnectError(100311, "modalErr:蓝牙未打开");
    }
  } else if (status == BLELocker.Status.adaperOpenFail) {
    getApp().hideLoading()
    wx.stopBluetoothDevicesDiscovery({
      success: function (e) {
        console.log(e);
      },
      complete: function (i) {
        console.log(i);
      }
    });
    wx.closeBLEConnection({
      deviceId: that.data.wxDeviceId,
      success: function (res) {
        console.log("close suc", res)
      },
      fail: function (res) {
        console.log("close err", res);
      }
    });
    wx.closeBluetoothAdapter({
      success: function (res) {
        console.log("closeA suc", res)
      },
      fail: function (res) {
        console.log("closeA err", res);
      }
    })
    if (that.data.curIsDirectCon) {
      app.globalData.isDirectConnect = true;
      connectShow.start();
      console.warn('连接失败,正在自动重连');
      BLELocker.setParams(function (status, data) {
        handleStatus(status, data)
      }, that);
      connectUtil.directBleCon(that.data.blueName, that.data.wxDeviceId)
      that.recordBlueConnectError(40010, 'direct connect start-adaperOpenFail:' + app.globalData.conErrDesc);
    } else {
      app.globalData.isDirectConnect = false;
      bleFailShow.modalMsgShow()
      that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: 'BT调起不成功' + pile_id + '（' + that.data.phoneInfo + '-100312)',
          desc: '请关闭蓝牙再打开后重试',
          retryConnect: true
        }
      })
      that.recordBlueConnectError(100312, "modalErr:初始化蓝牙适配器失败");
    }

  } else if (status == BLELocker.Status.bleNotSupportWXService || status == BLELocker.Status.bleNotSupportWXCharacteristic) {
    getApp().hideLoading()

    //1.关闭正在连接的提示对话框 2.弹出提示用户扫描的设备不支持微信协议（其实就是扫描了不支持微信协议连接的设备）
    leaseShow.resultShow("系统版本低,可能无法完成租赁")
  } else if (status == BLELocker.Status.bleReceiveAuthData) {
    getApp().hideLoading()

    //1.将正在连接的提示对话框中的提示语,变更为：连接成功,读取数据中,提示语请自行修改,这个时候正在发送95指令
    that.setData({
      loading_desc: "连接成功,数据读取中",
      loading_show: true
    });

  } else if (status == BLELocker.Status.bleConnectTimeout) {
    getApp().hideLoading()
    wx.stopBluetoothDevicesDiscovery({
      success: function (e) {
        console.log(e);
      },
      complete: function (i) {
        console.log(i);
      }
    });
    wx.closeBLEConnection({
      deviceId: that.data.wxDeviceId,
      success: function (res) {
        console.log("close suc", res)
      },
      fail: function (res) {
        console.log("close err", res);
      }
    });
    wx.closeBluetoothAdapter({
      success: function (res) {
        console.log("closeA suc", res)
      },
      fail: function (res) {
        console.log("closeA err", res);
      }
    })

    if (that.data.curIsDirectCon) {
      connectShow.start();
      app.globalData.isDirectConnect = true;
      BLELocker.setParams(function (status, data) {
        handleStatus(status, data)
      }, that);
      connectUtil.directBleCon(blueName, that.data.wxDeviceId)
      that.recordBlueConnectError(ConstantData.err_type.connect_direct_retry, '直连失败,自动重连');
      return;
    }

    var errCode = getTimeoutReasonCode();

    app.globalData.isDirectConnect = false;
    that.recordBlueConnectError(20003, "connect timeout:" + app.globalData.conErrDesc);

    //标记存储蓝牙连接失败的 时间
    colonyBlue.bleConFailMark();
    //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备超时,重新扫码
    that.setData({
      loading_show: false,
      openning_show: false,
    })

    console.log('监听到bleConnectTimeout', errCode);

    if (errCode == '10039') {
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: '请关闭蓝牙再打开后重试',
          desc_mini: 'receiveData不成功' + pile_id + '(' + that.data.phoneInfo + '-10039)',
          retryConnect: true
        }
      })
      that.recordBlueConnectError(10039, 'modalErr:接收数据时超时或报错');
    } else if (errCode == '100310') {
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          icon_name: 'icon-lanya',
          desc: '请在系统设置中打开微信的蓝牙权限后重试',
          desc_center: true,
          desc_mini: 'BT权限不成功' + pile_id + '(' + that.data.phoneInfo + '-100310)',
          open_ble_auth_show: true,
        }
      })
      that.recordBlueConnectError(100310, 'modalErr:ios13-蓝牙未打开');
    } else if (errCode.indexOf('10034') != -1) {
      getBLETimeoutReasonType(that);
    } else {
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: "请关闭蓝牙再打开后重试",
          icon_name: 'icon-lanya',
          desc_mini: 'BT调起不成功' + pile_id + '(' + that.data.phoneInfo + '-' + errCode + ')',
          desc_center: true,
          retryConnect: true
        }
      })
      that.recordBlueConnectError(errCode, 'modalErr:连接超时');
    }

    app.sendLog();
  } else if (status == BLELocker.Status.bleClosed) {
    getApp().hideLoading()

    //1.关闭正在连接的提示对话框（如果当前不是正在连接,是已经弹出租凭开锁对话框,则可以关闭租凭开锁对话框） 2.弹出提示用户蓝牙关闭,请重新扫码
    if (that.data.showModalStatus) {
      that.setData({
        showModalStatus: false,
        mapShowStatus: true,
      })
    }
    //1.关闭正在连接的提示对话框 2.弹出提示用户手机蓝牙未打开
    bleFailShow.modalMsgShow()
    that.setData({
      openning_show: false,
      loading_show: false,
      modal: {
        modal_show: true,
        desc: '蓝牙已关闭,重新打开扫码重试',
        confirm: true
      }
    })
  } else if (status == BLELocker.Status.bleOpened) {
    getApp().hideLoading()
    // wx.showToast({
    //   title: '手动打开蓝牙',
    // })

    //这里不需要做任何处理

  } else if (status == BLELocker.Status.bleSend85Timeout) { //暂未开启
    getApp().hideLoading()
    // wx.showToast({
    //   title: '发送85超时',
    // })

    bleFailShow.modalMsgShow()
    //1.关闭租凭开锁提示对话框 2.提示用户开锁超时,请重新扫码
    that.setData({
      showModalStatus: false,
      loading_show: false,
      mapShowStatus: true,
      openning_show: false,
      openLockLeaseOptStatus: true,
      modal: {
        modal_show: true,
        desc: '开锁超时,扫码归还后重试',
        desc_mini: 'send85Timeout' + pile_id + '-' + ConstantData.err_type.data_85_send_timeout,
        comfirm: true
      },
    });
    that.clear85Timer();
    that.recordBlueConnectError(ConstantData.err_type.data_85_send_timeout, 'modalErr:发送85超时' + ":" + app.globalData.devConnected);
  } else if (status == BLELocker.Status.ble85Back1Timeout) {
    getApp().hideLoading()
    app.globalData.isOpenLock = false;
    app.globalData.isConnecting = false;
    that.data.openLockStat = false; //当前已开锁完毕
    that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout, "85第1次回执超时,设备:mac=" + that.data.mac + ":" + app.globalData.devConnected)
    if (!app.globalData.devConnected) {
      that.clear85Timer();
      //重试开锁
      that.retry85('auto');
    } else if (that.data.hasOrderFlg && that.data.no_eject_flg || that.data.no_eject_back_flg == 1 || that.data.no_eject_flg) {
      let descMini = pile_id + '-' + ConstantData.err_type.data_85_back1_timeout_noeject_inner;
      statistic.noEjectDialog(that, descMini, '85第一条回执超时');
      that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout_noeject_inner, '85第一条回执超时，显示“未弹出弹框”');
    } else {
      let descMini = '85backTimeout' + pile_id + '-' + ConstantData.err_type.data_85_back1_timeout_else;
      statistic.noEjectDialog(that, descMini, '85第一条回执超时');
      that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout_else, 'modalErr:85第一条回执超时,请扫码归还后重试');
    }
    app.sendLog();
  } else if (status == BLELocker.Status.ble85Back2Timeout) {
    getApp().hideLoading()

    that.recordBlueConnectError(ConstantData.err_type.data_85_back2_timeout, "85第2次回执超时,显示“未弹出弹框”,设备mac=" + that.data.mac)
    that.data.openLockStat = false; //当前已开锁完毕
    app.globalData.isOpenLock = false;
    app.globalData.isConnecting = false;
    let descMini = pile_id + '-' + ConstantData.err_type.data_85_back2_timeout_noeject_inner;
    statistic.noEjectDialog(that, descMini, '85第2次回执超时');

  } else if (status == BLELocker.Status.bleSend95Timeout) {
    getApp().hideLoading()
    if (that.data.curBlueName && that.data.timeout95RetryFlg) {
      that.data.timeout95RetryFlg = false;
      that.data.retryCon = false; //刚开始还没有进行重试点击
      that.recordBlueConnectError(ConstantData.err_type.new_conf_95_timeout, '95发送超时,重新连接');
      //收到超时后，重置参数及关闭适配器等需要时间
      setTimeout(function () {
        connectBLEDevice(that.data.curBlueName);
      }, 250);
      return;
    }

    //标记存储蓝牙连接失败的 时间
    colonyBlue.bleConFailMark();
    bleFailShow.modalMsgShow()
    //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
    that.setData({
      showModalStatus: false,
      mapShowStatus: true,
      loading_show: false,
      modal: {
        modal_show: true,
        desc_mini: '95超时' + pile_id + '-' + ConstantData.err_type.data_95_send_timeout,
        desc: '连接失败,扫码重试',
        confirm: true
      }
    })

    that.recordBlueConnectError(ConstantData.err_type.data_95_send_timeout, 'modalErr:95超时');
    app.sendLog();
  } else if (status == BLELocker.Status.bleRecive95Timeout || status == BLELocker.Status.bleReciveAuto95Timeout) {

    //标记存储蓝牙连接失败的 时间
    colonyBlue.bleConFailMark();
    bleFailShow.modalMsgShow()
    //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
    that.setData({
      showModalStatus: false,
      mapShowStatus: true,
      loading_show: false,
      modal: {
        modal_show: true,
        desc_mini: '95接收超时' + pile_id + '-' + ConstantData.err_type.new_conf_95_receive_timeout,
        desc: '连接失败,扫码重试',
        confirm: true
      }
    })

    that.recordBlueConnectError(ConstantData.err_type.new_conf_95_receive_timeout, '95数据超时:' + status);

  } else if (status == BLELocker.Status.ble85Data || status == BLELocker.Status.ble88Data) {
    leaseShow.resultShow('开锁命令发送成功')

    that.data.isRetry85 = false;
    app.globalData.isOpenLock = false;
    //开锁完成隐藏可关闭蓝牙
    app.globalData.isConnecting = false;
    //隐藏可以关闭蓝牙
    that.data.hideIsDisconnectStat = true;
    that.recordBlueConnectError(ConstantData.err_type.data_85_suc, "85回执data-" + JSON.stringify(data))
    console.warn('---收到85', data);

    if (that.data.blankPileOpenFlg) {
      //非空桩开锁的可以跳转到开锁结果提示页面
      console.log("空桩开锁完成，不进行跳转")
      return;
    }
    //191101及之后的驱动
    if (data) {
      if (data.backSeq == 1 && !data.resultEnum) {
        //控制盒收到开锁命令
        that.data.openLockStat = true; //当前正在开锁
        connectShow.openLockingShow()
      } else if (data.backSeq == 2) { // mark: 开锁完成
        leaseShow.openLockOverTip()
        that.setData({
          openning_show: false
        })
        //开锁结束
        that.clear85Timer();
        BLELocker.stop85Back1Timeout();
        BLELocker.stop85Back2Timeout();
        that.data.openLockStat = false; //当前开锁结束
        if (data.noEject == 1) { //设备未弹出
          leaseShow.resultHide();
          let descMini = pile_id + '-' + ConstantData.err_type.data_85_back2_noeject_inner;
          statistic.noEjectDialog(that, descMini, data);
          that.recordBlueConnectError(ConstantData.err_type.data_85_back2_noeject_inner, '85第二条回执提示未弹出，显示“未弹出弹框”');
        } else {
          console.log("开锁后断开蓝牙--ccc->")
          app.globalData.isConnecting = false;
          BLELocker.disconnect('index3456')

          if (!that.data.equId || !that.data.opentime) {
            that.data.equId = wx.getStorageSync('equId');
            that.data.opentime = wx.getStorageSync('opentime');
          }
          that.data.isToTipBackSucPage = true
        }

      } else {
        leaseShow.openLockOverTip()
        console.log('UI层收到85数据', data)
        that.data.openLockStat = false; //当前开锁结束
        if (!that.data.equId || !that.data.opentime) {
          that.data.equId = wx.getStorageSync('equId');
          that.data.opentime = wx.getStorageSync('opentime');
        }
        that.data.isToTipBackSucPage = true
      }
    } else {
      that.data.openLockStat = false; //当前开锁结束
      if (that.data.hasOrderFlg && that.data.no_eject_flg || that.data.no_eject_back_flg == 1) {
        let descMini = pile_id + '-' + ConstantData.err_type.data_85_null_inner;
        statistic.noEjectDialog(that, descMini, '85回执为空');
        that.recordBlueConnectError(ConstantData.err_type.data_85_null_inner, '85回执为空，显示“未弹出弹框”');
      } else {
        bleFailShow.modalMsgShow()
        //1.关闭租凭开锁提示对话框 2.提示用户开锁失败,请重新扫码
        that.setData({
          showModalStatus: false,
          loading_show: false,
          mapShowStatus: true,
          openning_show: false,
          openLockLeaseOptStatus: true,
          modal: {
            modal_show: true,
            desc: '开锁失败,扫码归还后重试',
            desc_mini: '85null' + pile_id + '-' + ConstantData.err_type.data_85_null_else,
            comfirm: true
          },
        })
        that.recordBlueConnectError(ConstantData.err_type.data_85_null_else, 'modalErr:85null');
        app.sendLog();
      }
    }

  } else if (status == BLELocker.Status.ble95Data) {
    wx.removeStorageSync('retryConCounts');
    app.globalData.conIsSuc = true;
    if (app.globalData.conTimeoutTimer) {
      clearTimeout(app.globalData.conTimeoutTimer);
    }
    if (app.globalData.data95ReceiveTimer) {
      clearTimeout(app.globalData.data95ReceiveTimer);
    }
    if (app.globalData.directConnectTimer) {
      clearTimeout(app.globalData.directConnectTimer);
    }
    if (app.globalData.auto95RecTimer) {
      clearTimeout(app.globalData.auto95RecTimer);
    }

    app.globalData.conTimer?.clearConTimer()

    //设置全局的首页对象句柄，便于开锁85时进行调用
    console.warn('ble95Data---->', data);
    let conTimeLen = app.globalData.startConTime ? (new Date().getTime() - app.globalData.startConTime) : -1;
    let err95TypeVal = that.data.retry95Flg ? ConstantData.err_type.retry_send_95_log : ConstantData.err_type.receive_95_time;
    that.recordBlueConnectError(err95TypeVal, 'ble95Data:' + conTimeLen);
    //数据读取中
    if (that.data.curIsDirectCon && app.globalData.isDirectConnect) {
      that.recordBlueConnectError(40012, 'direct connect success');
    }
    let nowTime = new Date().getTime();

    //防止连续95数据 start
    if (that.data.data95Time && (nowTime - that.data.data95Time < that.data.many95DataInterval)) {
      console.log('操作频繁');
      that.data.data95Time = nowTime;
      that.recordBlueConnectError(ConstantData.err_type.data_95_repeat, '连续95数据,已忽略');
      return;
    }
    that.data.data95Time = nowTime;
    //防止连续95数据 end

    if (that.data.send85Time && (nowTime - that.data.send85Time < that.data.blue95Interval)) {
      console.log('操作频繁，忽略95数据');
      that.setData({
        loading_show: false
      })
      wx.showToast({
        title: '您的操作过于频繁，请稍候再试',
        icon: 'none'
      })
      return;
    }
    //数据已返回开始处理
    connectShow.handle95Data()
    if (data == null) {
      bleFailShow.modalMsgShow()
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
      that.setData({
        showModalStatus: false,
        mapShowStatus: true,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: '95null' + pile_id + '-' + ConstantData.err_type.data_95_null,
          desc: '连接失败,请扫码重试',
          confirm: true
        }
      })
      that.recordBlueConnectError(ConstantData.err_type.data_95_null, 'modalErr:95null');
      app.sendLog();
    } else {
      getApp().hideLoading()
      that.data.rfId = data.rfid
      that.data.elecInt = data.electrict; //归位桩剩余电量
      console.log("处理95指令接收的数据", data)
      let location = wx.getStorageSync('location')
      data.location = location
      that.data.static95Data = data;
      console.log("处理95指令接收的数据2", data)
      let dataType = "95data";
      statistic.statisticData(dataType, JSON.stringify(that.data.static95Data));

      if (data.mac && that.data.conMac && data.mac != that.data.conMac) {
        BLELocker.disconnect('condev1611', 'stopConnect');
        that.recordBlueConnectError(ConstantData.err_type.data_95_no_lastest, '不是最新扫码95数据:' + data.mac + "," + that.data.conMac);
        return;
      }

      if (data.motorStat == 1) {
        bleFailShow.modalMsgShow()
        that.setData({
          showModalStatus: false,
          mapShowStatus: true,
          loading_show: false,
          openning_show: false,
          modal: {
            modal_show: true,
            desc: '设备重启中，请稍候再试',
            desc_mini: pile_id + '-' + ConstantData.err_type.data_95_motorunning,
            confirm: true
          }
        });
        that.recordBlueConnectError(ConstantData.err_type.data_95_motorunning, "95马达状态motorStat-" + data.motorStat + '-rfid-' + data.rfid);
        return;
      }

      if (that.data.canRetry85 && that.data.isScanBack != 'true') {
        //如果是三分钟之内，显示未弹出弹框
        console.warn('--未弹出，重新连接成功，发送85');
        if (that.data.retryType85 == 'auto') {
          that.recordBlueConnectError(ConstantData.err_type.data_95_85_retry_atuo, '自动重试租借，重新连接成功，开始发送85');
        } else {
          that.recordBlueConnectError(ConstantData.err_type.data_95_85_retry, '用户点击重试租借，重新连接成功，开始发送85');
        }
        that.data.canRetry85 = false;
        that.send85Command();
        return;
      }

      if (that.data.pileLocation != undefined && that.data.pileLocation != null) {
        data.location = that.data.pileLocation;
      }
      let version = BLELocker.getDriverVersion();
      if (!data.pile_ver) {
        data.pile_ver = version;
      }

      let sysInfo = wx.getStorageSync("systeminfo");
      data.phoneType = sysInfo.model;
      var electrict = data.electrict; //归位桩剩余电量
      let noEject = data.chairIsEjectLose;
      let no_eject_times = 0;
      if (noEject == 1) {
        no_eject_times = wx.getStorageSync('no_eject_times') || 1;
        wx.setStorageSync('no_eject_times', no_eject_times + 1)
      } else {
        wx.removeStorageSync('no_eject_times')
      }
      let user_no_back = wx.getStorageSync('user_no_back')
      console.log('no_eject_times============', no_eject_times, user_no_back)
      if (no_eject_times > 2 && !user_no_back) {
        bleFailShow.modalMsgShow()
        that.setData({
          showModalStatus: false,
          mapShowStatus: true,
          loading_show: false,
          openning_show: false,
          modal: {
            modal_show: true,
            desc: '请换一台设备租赁',
            desc_mini: 'noEject' + pile_id + '-' + ConstantData.err_type.data_95_noeject,
            confirm: true
          }
        });
        that.recordBlueConnectError(ConstantData.err_type.data_95_noeject, "modalErr-mac=" + data.mac);
        return;
      }


      if (app.globalData.conBlueVer && app.globalData.conBlueVer == 'om-phy-1.0') {} else {
        if (app.globalData.connectSucType == 'ble') {
          //发送控制盒广播配置命令
          BLELocker.sendBroadcastConfCommand();
          if (that.data.isSend98Cmd) {
            setTimeout(function () {
              //发送98获取数据
              that.send98Command(version);
            }, 200);
          }
        }
      }

      that.setData({
        hookStatus: data.hookStatus,
        switchStatus: data.chairSwitchSatus,
        didiStat: data.programRestartTimes,
        // picTip: picTipDesc,
        mac: data.mac,
        rfid: data.rfid,
        rfidIsCache: data.rfidIsCache ? data.rfidIsCache : -100
      })
      var mac = data.mac;
      console.log("mac=" + mac + ",left electrit -->" + electrict)
      var rfId = data.rfid;
      var costTime = data.costTime;
      //存储控制盒上报的记录的时长
      that.data.conBoxCostTime = data.costTime;
      console.log("rfId=" + rfId + ",costTime=" + costTime)

      that.data.blankPileOpenFlg = false;

      //空桩开锁权限判断,有空桩开锁权限且rfid不识别或rfid从缓存中读取的，可直接进行开锁
      let isBlankOpen = (data.rfidIsCache == 1 || 'FFFFFFFF' == rfId) && that.data.isNoRfidOpen == 1; //空桩开锁权限
      isBlankOpen = that.data.isNoRfidOpen == 2 || isBlankOpen; //存在辅助开锁权限的不做空桩判断可直接开锁20200805145400
      if (isBlankOpen) {
        wx.showLoading({
          title: '检测中..',
        });

        setTimeout(function () {
          getApp().hideLoading();
          if (that.data.isColonyCon) {
            colonyBlue.openLock(that.data.mac, that, 1);
          } else {
            that.data.blankPileOpenFlg = true;
            that.send85Command();
          }
          that.setData({
            loading_show: false,
            openning_show: false
          })
          wx.showToast({
            title: '开锁完成',
          })

        }, 2000);
      } else if ('FFFFFFFF' == rfId && that.data.pageType != 1) { //轮椅未识别
        let rfid_error_time = wx.getStorageSync('rfid_error_time') || 1;
        wx.setStorageSync('rfid_error_time', rfid_error_time + 1);
        let errType = '';
        //第3次不识别
        if (rfid_error_time > 2) {
          bleFailShow.modalMsgShow()
          //判断是否归还
          if (user_no_back) {
            errType = ConstantData.err_type.data_95_rfid_back_times;
            that.setData({
              showImage: '../../image/end_chain.png',
              modal: {
                desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还",
                desc_mini: "rfid不识别 " + pile_id + "-" + errType,
                modal_show: true,
                contact: true
              }
            })
          } else {
            errType = ConstantData.err_type.data_95_rfid_rent_times;
            let desc = that.data.connectType && that.data.connectType == '归还' ? '未识别到设备，请联系客服' : '请换一个设备租赁';
            that.setData({
              showImage: '../../image/end_chain.png',
              modal: {
                desc: desc,
                desc_mini: "rfid不识别 " + pile_id + "-" + errType,
                modal_show: true,
                confirm: true,
              }
            })
          }
          BLELocker.disconnect('index4608', 'stopConnect');
        } else {
          bleFailShow.modalMsgShow()
          //判断是否归还
          if (user_no_back) {
            errType = ConstantData.err_type.data_95_rfid_back;
            let desc = '请将轮椅靠右摆放且听到“设备已归还”后，再点击重试！'
            if (that.data.pile_type) {
              desc = '请将轮椅摆正。然后往里推着轮椅，听到“设备已归还”后，再点击重试。'
            }
            that.setData({
              showImage: '../../image/end_chain.png',
              modal: {
                desc: desc,
                desc_mini: "rfid不识别 " + pile_id + "-" + errType,
                retry95: true,
                img1_show: true,
                modal_show: true,
              }
            })
          } else {
            if (data.chairSwitchSatus == 0) {
              errType = ConstantData.err_type.data_95_rfid_rent_noInsert;
              that.setData({
                showImage: '../../image/end_chain.png',
                modal: {
                  modal_show: true,
                  desc: '当前桩上没有设备，请换一个有设备的桩租赁哦。',
                  desc_mini: "rfid不识别 inSwitch " + pile_id + "-" + errType,
                  cancel: true,
                  reScan: true,
                }
              })
              BLELocker.disconnect('index4628', 'stopConnect');
            } else {
              errType = ConstantData.err_type.data_95_rfid_rent;
              let desc = '请将轮椅左右摇晃并靠右摆放后点击重试'
              if (that.data.pile_type) {
                desc = '请将轮椅摆正。然后往里推着轮椅点击重试。'
              }
              that.setData({
                showImage: '../../image/end_chain.png',
                modal: {
                  desc: desc,
                  modal_show: true,
                  desc_mini: "rfid不识别 " + pile_id + "-" + errType,
                  retry95: true,
                  img1_show: true,
                }
              })
            }

          }
        }
        if (errType) {
          that.recordBlueConnectError(errType, "modalErr:rfid不识别");
        }
      } else if ('00000000' == rfId && data.chairSwitchSatus == 0) { //共享陪护床
        bleFailShow.modalMsgShow()
        if (user_no_back && wx.getStorageSync('user_no_back').data.noBack.lockType == '宜家锁') {
          that.setData({
            showyijia: true,
            modal: {
              desc: "请确认设备已按照图示锁好后\n点击重试。",
              desc_mini: "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc,
              modal_show: true,
              contact: true,
            }
          })
        } else if (user_no_back && wx.getStorageSync('user_no_back').data.noBack.lockType != '宜家锁') {
          that.setData({
            modal: {
              desc: "请检查设备是否已经锁好\n如果已锁好，请联系客服帮您归还。",
              desc_mini: "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc,
              modal_show: true,
              contact: true,
            }
          })
        } else { // mark: 陪护椅锁95开关错误
          if (that.data.showStat.openOverConfirm) {
            console.log("开锁完成，收到的95日志")
            return
          }
          that.setData({
            modal: {
              desc: "该设备故障，请更换一个设备使用！",
              desc_mini: "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc,
              modal_show: true,
              confirm: true
            }
          })
        }
        that.recordBlueConnectError(ConstantData.err_type.data_95_phc, "modalErr:陪护床插入开关错误");
      } else if (that.data.isJudgeInsertSwitch && that.data.isNoRfidOpen != 1 && data.chairSwitchSatus == 0 && user_no_back && data.programRestartTimes != 1 && that.data.pageType != 1) { //isJudgeInsertSwitch:判断插入开关;isNoRfidOpen:空桩开锁;
        BLELocker.disconnect('index4630', 'stopConnect');
        that.recordBlueConnectError(10060, '用户中断连接4630');
        //用户归还且插入状态不对
        let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1;
        wx.setStorageSync('insert_fail_time', insert_fail_time + 1);
        bleFailShow.modalMsgShow()
        let errType = '';
        //第3次
        if (insert_fail_time > 2) {
          errType = ConstantData.err_type.data_95_noInsert_times;
          that.setData({
            showImage: '../../image/end_chain.png',
            modal: {
              desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还。",
              desc_mini: "inSwitch " + pile_id + "-" + errType,
              modal_show: true,
              contact: true
            }
          })
        } else {
          errType = ConstantData.err_type.data_95_noInsert;

          that.setData({
            showImage: '../../image/end_chain.png',
            modal: {
              desc: "1、请检查设备是不是已经锁好\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。",
              desc_mini: "inSwitch " + pile_id + "-" + errType,
              modal_show: true,
              img2_show: true,
              retry95: true,
              desc_center: false,
            }
          })
        }

        if (errType) {
          that.recordBlueConnectError(errType, "modalErr:插入开关错误");
        }
      } else {
        wx.removeStorageSync('rfid_error_time');
        wx.removeStorageSync('insert_fail_time');

        if (that.data.canceledConnect) {
          that.recordBlueConnectError(10061, "用户中断连接1");
          wx.showModal({
            title: '连接中断',
            showCancel: false,
            content: '连接中断，请重新扫码',
            complete: (res) => {
              if (res.confirm) {}
            }
          })
          return;
        }
        openOrReturnEquitment(rfId, mac, costTime); //开锁或归还
      }
    }
  } else if (status == BLELocker.Status.ble75zeroData) {
    //75第0包数据
    console.log("接收到格子柜第0包数据", data, app.globalData.data75ReceiveTimer);
    if (app.globalData.data75ReceiveTimer) {
      clearTimeout(app.globalData.data75ReceiveTimer);
    }
    if (app.globalData.conTimeoutTimer) {
      clearTimeout(app.globalData.conTimeoutTimer);
      app.globalData.conTimeoutTimer = null;
    }
    //发送获取各个门的状态信息
    if (data) {
      that.setData({
        openning_show: false,
        connectDesc: "数读设备成功,读取格子状态中...",
        loading_show: true,
        loading_desc: '读取格子状态中01...',
      });
      that.data.latticeCabinetData = new Object();
      that.data.latticeCabinetData.latticeData = data;
      that.data.latticeCabinetData.doorDataList = new Array();
      let equStatData = data.equStat;
      let doorCount = parseInt(equStatData.maxDoorCount, 16);
      console.log("格子柜的在线门数量---->", doorCount, equStatData.maxDoorCount);

      that.data.data75NReceiveTimer = setTimeout(function () {
        console.log("75N包数据接收超时...", callback);
        handleStatus(BLELocker.Status.bleRecive75NTimeout);
      }, 8000);

      that.send75Command("01");
      //  for(var i=1;i<=doorCount;i++) {
      //     let doorNum = i < 10 ? "0" + i : i;
      //     setTimeout(function(){
      //       that.send75Command(doorNum);
      //     },100);            
      //  }
    } else {
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取柜信息失败,请扫码重试',
        success(res) {}
      })
    }

  } else if (status == BLELocker.Status.ble75NData) {
    //75第N包数据
    console.log("接收到格子柜第N包数据", data, that.data.latticeCabinetData, app.globalData.data75ReceiveTimer);

    if (data) {
      if (!that.data.latticeCabinetData) {
        that.data.latticeCabinetData = new Object();
      }
      if (!that.data.latticeCabinetData.doorDataList) {
        that.data.latticeCabinetData.doorDataList = new Array();
      }
      that.data.latticeCabinetData.doorDataList.push(data);
      let doorMaxCount = that.data.latticeCabinetData.latticeData ? parseInt(that.data.latticeCabinetData.latticeData.equStat.maxDoorCount, 16) : 0;
      let getDoorCount = that.data.latticeCabinetData.doorDataList.length;
      if (doorMaxCount == getDoorCount) {
        //已接收完门的总数量
        if (that.data.data75NReceiveTimer) {
          clearTimeout(that.data.data75NReceiveTimer);
        }

        //记录格子柜信息日志
        let mac = that.data.conMac;
        that.data.latticeCabinetData.mac = mac;
        statistic.statisticData("75data", JSON.stringify(that.data.latticeCabinetData));

        //开始请求是否可以开锁          
        let doorNumArr = new Array();
        let doorRfidArr = new Array();
        for (var i = 0; i < getDoorCount; i++) {
          let doorData = that.data.latticeCabinetData.doorDataList[i].doorStat;
          let doorNum = doorData.doorNum;
          let isOnline = doorData.doorStat;
          let rfid = doorData.rfid;
          let binStat = doorData.binStat;
          if (isOnline != 'FF') {
            let num = parseInt(doorNum, 16);
            doorNumArr.push(num);
            let doorRfidStr = num + ":" + rfid + ":" + binStat;
            doorRfidArr.push(doorRfidStr);
          }
        }
        let doorNumStr = doorNumArr.join(',');
        let doorRfidStr = doorRfidArr.join(',');
        that.setData({
          openning_show: false,
          connectDesc: "门状态读取成功,开始请求开锁信息...",
          loading_show: true,
          loading_desc: '请求开锁信息中...',
        });
        //进行开锁
        that.latticeOpen(mac, doorNumStr, doorRfidStr);
      } else {
        let doorNum = parseInt(data.doorStat.doorNum, 16) + 1;
        let doorNumHex = doorNum.toString(16);
        doorNumHex = doorNumHex.length == 1 ? "0" + doorNumHex : doorNumHex;
        that.setData({
          openning_show: false,
          connectDesc: "数读设备成功,读取格子状态中" + doorNumHex + "...",
          loading_show: true,
          loading_desc: '读取格子状态中' + doorNumHex + '...',
        });
        setTimeout(() => {
          that.send75Command(doorNumHex);
        }, 100);

      }
    } else {
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取锁信息失败,请扫码重试',
        success(res) {}
      })
    }

  } else if (status == BLELocker.Status.ble98Data) {
    //98数据记录
    let dataType = "98data";
    console.log("------data>", data);
    data.push(that.data.mac);
    data.push(that.data.rfId);
    console.log("---98data,", data);

    statistic.statisticData(dataType, JSON.stringify(data));
  } else if (status == BLELocker.Status.bleRecive75Timeout) {
    //蓝牙75第0包接收超时
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '获取设备信息超时,请扫码重试',
      success(res) {}
    })
  } else if (status == BLELocker.Status.bleRecive75NTimeout) {
    //蓝牙75第N包接收超时
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '获取锁信息超时,请扫码重试',
      success(res) {}
    })
  } else if (status == BLELocker.Status.bleRecive76Timeout) {
    that.setData({
      loading_show: false,
    });
    //蓝牙75第N包接收超时
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '开锁响应超时,如果未开门,请扫码重试',
      success(res) {}
    })
  } else if (status == BLELocker.Status.ble76Data) {
    if (app.globalData.data76ReceiveTimer) {
      clearTimeout(app.globalData.data76ReceiveTimer);
      app.globalData.data76ReceiveTimer = null;
    }
    //格子柜开锁结果返回数据
    console.log("格子柜开锁结果返回数据", data);
    that.setData({
      openning_show: false,
      loading_show: false,
    });
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '门已打开成功，谢谢使用!',
      success(res) {}
    })
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index5445');
    let mac = that.data.conMac;
    data.mac = mac;
    statistic.statisticData("76data", JSON.stringify(data));
  } else if (status == BLELocker.Status.bleOneMorePhyLockStatusData) {
    //one more 陪护椅锁状态信息
    console.log("one more 陪护椅锁状态信息 处理-->", data);
    if (data.hookStatus == 1) {
      //锁舌未弹出,发送锁舌弹出命令后再查询收费规则
      BLELocker.oneMorePhyBleLock();
      setTimeout(() => {
        handleStatus(BLELocker.Status.ble95Data, data);
      }, 100);
    } else {
      //相当于95命令，进行收费规则请求然后，点击开锁进行开锁
      handleStatus(BLELocker.Status.ble95Data, data);
    }
  } else if (status == BLELocker.Status.bleReciveOneMorePhyTokenTimeout) {
    that.setData({
      loading_show: false,
    });
    //接收one more的陪护椅token超时   
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '设备token响应超时,请扫码重试',
      success(res) {}
    })
  } else if (status == BLELocker.Status.bleSendOneMorePhyUnlockTimeout) {
    //one more 陪护椅开锁超时
    that.setData({
      loading_show: false,
      openning_show: false,
    });
    //接收one more的陪护椅token超时   
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '开锁超时,请扫码重试',
      success(res) {}
    })
  } else if (status == BLELocker.Status.bleOneMorePhyUnLockData) {
    //one more 陪护椅开锁结果
    console.log("one more 陪护椅开锁结果：", data);
    handleStatus(BLELocker.Status.ble88Data, data);
  } else if (status == BLELocker.Status.bleSend95DevNull || status == BLELocker.Status.bleSend95ConDis) {
    //发送95指令时设备信息为空或蓝牙断开连接
    that.setData({
      loading_show: false,
    });
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index5430');
    that.recordBlueConnectError(ConstantData.err_type.data_95_send_fail, "发送95失败status=" + status);

    //接收one more的陪护椅token超时   
    wx.showModal({
      showCancel: false,
      title: '温馨提示',
      content: '获取设备数据失败,请扫码重试',
      success(res) {}
    })

    clearTimeout(app.globalData.data95ReceiveTimer);
    clearTimeout(app.globalData.auto95RecTimer);
  }

}



/**
 * 等待接收蓝牙消息,进行开锁或归还操作
 * @param eqId
 * @param hid
 * @param costTime
 */
function openOrReturnEquitment(rfId, mac, costTime) {
  var that = app.globalData.newConThat
  //服务端接口存在没有上传的数据为空
  if (!rfId) {
    //将接收到95数据的赋值
    rfId = that.data.rfId;
  }
  if (!mac) {
    //将扫码时获取的mac赋值
    mac = that.data.conMac;
  }
  if (!costTime) {
    //将接收到95数据时的赋值
    costTime = that.data.conBoxCostTime;
  }

  //请稍等,处理数据中...
  connectShow.getRuleOrBack()
  that.data.openLockGetData = null
  that.data.reqOpenLockTime = null
  that.data.openTime = null
  app.executeRequest(function (header) {
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/open_lock',
      method: 'post',
      header: header,
      data: {
        depositAutoBack: that.data.depositAutoBack,
        rfId: rfId,
        mac: mac,
        costTime: costTime,
        refund: that.data.refund,
        hookStatus: that.data.hookStatus,
        switchStatus: that.data.switchStatus,
        didiStat: that.data.didiStat,
        rfidIsCache: that.data.rfidIsCache,
        isScanBack: that.data.isScanBack,
      },
      success: function (res) {
        that.data.openLockGetData = res
        that.data.conMac = mac
        //校验服务器
        if (!that.data.reqOpenLockTime) {
          that.data.reqOpenLockTime = new Date().getTime()
        } else {
          let diff = new Date().getTime() - that.data.reqOpenLockTime
          if (diff < 5000) {
            console.log('服务返回两次open_lock:', res)
            return
          }
        }

        handleOpenLockData()
      },
      fail: function (res) { // mark: 请求open_lock接口失败
        wx.showToast({
          title: '网络异常请重试',
        })
        leaseShow.netFail("网络异常，请重新扫码租借")
      },
      complete: function (res) {
        if (that.data.canceledConnect) {
          that.recordBlueConnectError(10062, "用户中断连接2");
          return;
        }
        that.setData({
          loading_show: false
        })

        setTimeout(function () {
          that.recordBlueConnectError(ConstantData.err_type.open_lock_res, "开始请求是否符合开锁租赁条件" + rfId + ' 请求结果:' + (res.data ? res.data.rst : '空'));
        }, 300);

      }
    })

  })

}

// mark: 处理开锁数据信息
function handleOpenLockData() {
  let that = app.globalData.newConThat
  let mac = that.data.conMac
  let res = that.data.openLockGetData
  console.warn("开锁访问服务返回结果===========res=", res)

  common.clearConTimeCountTimer('112');

  let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
  let errType = '';
  let netErr = app.handleRes(res, that);
  if (netErr) {
    return
  }
  if (that.data.canceledConnect) {
    that.recordBlueConnectError(10062, "用户中断连接2");
    return;
  }
  //记录校验结果日志
  setTimeout(function () {
    that.recordBlueConnectError(ConstantData.err_type.open_lock_suc, "返回校验结果:" + JSON.stringify(res.data));
  }, 1000);

  var data = res.data
  that.data.leftFreeTimeTipContent = data.leftFreeTimeTipStr
  that.data.no_eject_flg = data.no_eject;
  if (data.backSucVoiceUrl) {
    that.data.voiceTempFilePath = data.backSucVoiceUrl;
  }
  //未准确插入归位桩
  if (data.rst == -133) {
    //记录未准确插入桩的时间
    errType = ConstantData.err_type.open_lock_133;
    that.recordReturnBlueTimeoutError(2, '');
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index2022');

    var nophone = app.getUserLoginNoPhone();
    if (nophone == null || nophone == undefined || nophone == 1) {
      wx.setStorageSync("alertBoxTipContent", data.errInfo);
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'no_return_blue_timeout',
        loading_show: false
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return;
    }

    leaseShow.resultShow(data.errInfo + errType)

    return
  }

  if (data.rst == 12) { //帮代租设备已成功归还 // mark: 帮代租设备已成功归还
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index2043')
    leaseShow.resultShow('帮代租设备已成功归还')
    return
  }

  if (data.rst == '-138') { //帮代租设备已成功归还
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index2676')
    that.setData({
      showDialog: true,
      alertBoxTipContent: data.eqId,
      // msgRst: 6,
      alertBoxBtnName: '重新扫码',
      wxDeviceId: data.deviceId,
      wxConnType: data.connType
    })
    return
  }

  if (data.rst == 13) {
    errType = ConstantData.err_type.open_lock_13;
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index2280')
    bleFailShow.modalMsgShow()
    that.setData({
      modal: {
        modal_show: true,
        desc: data.errInfo ? data.errInfo : '当前时间不可租借' + errType,
        confirm: true
      }
    })
    return;
  }
  if (data.rst == 14) {
    errType = ConstantData.err_type.open_lock_14;
    bleFailShow.modalMsgShow()
    that.setData({
      modal: {
        modal_show: true,
        desc: data.errInfo ? data.errInfo : '您的操作过于频繁，请稍候再试' + errType,
        confirm: true
      }
    })
    return;
  }
  console.log('elecInt---------homeMinLeftElectricity', that.data.elecInt, data.homeMinLeftElectricity)
  if (that.data.elecInt < data.homeMinLeftElectricity) { // mark: 正安排更换电池
    errType = ConstantData.err_type.open_lock_15;
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index2056')
    leaseShow.resultShow('正安排更换电池,请租赁其他设备' + pile_id + '-' + errType)
    that.recordBlueConnectError(errType, "开锁:正安排更换电池,请租赁其他设备,mac=" + mac)

    return;
  }

  //判断是否存在绑定的账号，存在则弹出选择的列表 // mark: 是否存在帮代借账号
  var bindUserList = data.bindUserInfoList
  var agentEmployerList = data.agentEmployerList
  if (agentEmployerList && agentEmployerList.length > 0) {
    var sureLeaseTipInfo = '请提醒用户及时归还'
    //门诊爱心租赁列表
    that.setData({
      bindUserType: 2,
      bindUserListStatus: true,
      mapShowStatus: false,
      showModalStatus: false,
      agentLeaseSelStatus: false,
      bindUserList: agentEmployerList,
      wxDeviceId: data.deviceId,
      wxConnType: data.connType,
      wxEqId: data.eqId,
      wxHid: data.hid,
      wxEqTid: data.eqTid,
      leftTimeLenStr: sureLeaseTipInfo
    })
    return
  }

  if (bindUserList && bindUserList.length > 0) {
    //包时卡绑定用户
    that.setData({
      bindUserType: 1,
      bindUserListStatus: true,
      mapShowStatus: false,
      showModalStatus: false,
      agentLeaseSelStatus: false,
      bindUserList: bindUserList,
      wxDeviceId: data.deviceId,
      wxConnType: data.connType,
      wxEqId: data.eqId,
      wxHid: data.hid,
      wxEqTid: data.eqTid
    })
    return
  }

  var systemInfo = wx.getStorageSync('systeminfo');
  var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
  var isAllowNoDeposit = isCouldNoDeposit && data.wxNoDeposit == 1;
  console.log("-----isAllowNoDeposit=", isAllowNoDeposit);
  that.setData({
    isAllowNoDeposit: isAllowNoDeposit
  })

  let equTipInfo = data.equTipInfo;
  if (equTipInfo) {
    that.setData({
      //提示的图片列表
      imgUrls: equTipInfo.tipImgList,
      //是否显示轮播图的点
      indicatorDots: equTipInfo.tipImgList.lenght > 1,
      //提示的标题
      tipTitle: equTipInfo.title,
      //提示描述说明信息
      tipList: equTipInfo.tipList,
    })
  }

  if (data.rst == 0) {
    //已支付押金
    console.log("paied deposit getOpenLockData----", data)
    if (data.isSilenceBack == 1) {
      that.setData({
        isReturn: that.data.isReturn + 1
      })
      leaseShow.backSucShow()
      BLELocker.disconnect('newCon1506')
      that.recordBlueConnectError(ConstantData.err_type.open_lock_slience_back, '静默归还');
      return
    }

    that.setData({
      isReturn: 0
    })
    wx.removeStorageSync('no_eject_times')
    wx.setStorageSync("no_pay_deposit", 0);
    that.setData({
      //设备押金                            
      equDeposit: data.deposit,
      bindUserType: 0,
      isPayDeposit: true,
      openLockLeaseOptStatus: true,
      rulePic: data.rulePic && data.rulePic.length > 0 ? data.rulePic : null,
      chargeRuleTitle: data.chargeRuleTitle,
      equTypeName: data.tName,
      chargeContent: data.chargeRuleInfo,
      closeTipInfo: data.closeDoorTip,
      mapShowStatus: false,
      bindUserListStatus: false,
      agentLeaseSelStatus: false,
      bindUserList: [],
      wxDeviceId: data.deviceId,
      wxConnType: data.connType,
      wxEqId: data.eqId,
      wxHid: data.hid,
      wxEqTid: data.eqTid,
      serviceUuid: data.homing_uuid,
      homingFEC7: data.homing_FEC7,
      homingFEC8: data.homing_FEC8,
      homingFEC9: data.homing_FEC9,
      ruleList: data.ruleList,
      ruleDesc: data.ruleDesc,
      leaseMaxPriceStr: data.leaseMaxFeeStr,
      loading_show: false,
    })

    console.log('open_lock访问返回--》', that.data.pileState, that.data.isScanBack)
    if (that.data.pileState == 2 && that.data.isScanBack != 'true') {
      that.setData({
        showUnlock: true,
        showStat: {
          connect: true,
          conStatDesc: "点击开锁，设备即可弹出",
        }
      })
      return
    }

    if (that.data.bleDepositPaySuc) {
      //标记押金支付成功后由于蓝牙断开重新连接
      that.data.read = true;
      openLock();
      return;
    }
    toPayOrAuthScore()
  } else {
    console.log("openLock statRst=" + data.rst)
    if (data.rst == 11) { //租赁记录支付完成        
      //归还数据信息
      that.data.backDataInfo = data

      leaseShow.backSucShow()
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2179')
      that.setData({
        msgRst: 1,
        alertBoxBtnName: '确  定',
        wxDeviceId: data.deviceId,
        wxConnType: data.connType,
        refundTip: that.data.refund, //1在租赁页面弹toast提示
        refund: 0,
        isBackChairStatus: false,
        refundEqTid: data.eqTid
      })

      that.data.isToTipBackSucPage = true

    } else if (data.rst == 1) { //归还设备,跳转到租金列表进行支付
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2198')
      that.setData({
        msgRst: 1,
        isBackChairStatus: false,
        alertBoxBtnName: '确  定',
        wxDeviceId: data.deviceId,
        wxConnType: data.connType
      })
      let rentInfo = {};
      rentInfo.backTime = data.backTime;
      rentInfo.borrowTime = data.openTime;
      rentInfo.costTime = data.timeLenStr;
      rentInfo.deposit = data.deposit;
      rentInfo.orderCode = data.orderCode;
      rentInfo.rent = data.rent;
      rentInfo.noPayTitle = data.noPayTitle;
      rentInfo.priceLabel = data.priceLabel;
      rentInfo.orderType = data.orderType;
      rentInfo.inCycleLeaseTimeLen = data.inCycleLeaseTimeLen || '';
      rentInfo.inCycleRecordInfoList = data.inCycleRecordInfoList || [];
      rentInfo.noPayDepositTip = data.noPayDepositTip;
      rentInfo.depositBackSuc = data.isAutoRefund;
      rentInfo.backSucVoiceUrl = data.backSucVoiceUrl;
      wx.navigateTo({
        url: '../../../pages/index/no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
      })

    } else if (data.rst == 2) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
      errType = ConstantData.err_type.open_lock_2;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2214')
      if (data.leaseNoBackInfo) {
        //未归还的
        if (that.data.pt == 'noback' || (data.eqId && data.eqId != data.leaseNoBackInfo.equId)) {
          bleFailShow.modalMsgShow()
          that.setData({
            modal: {
              modal_show: true,
              desc_mini: errType,
              desc: "您有一台设备正在租借中！我们不支持同时租2个以上设备哦，请将前一台设备归还可继续租借。", // + data.leaseNoBackInfo.equId + "，这个L" + data.leaseNoBackInfo.equId + "轮椅锁在哪个桩位上，就扫哪个桩位玻璃面板上大的二维码就可以归还成功了",
              confirm: true,
              desc_center: true
            }
          })
        } else {
          console.log("跳转到未归还页面--------------------------------》")
          wx.navigateTo({
            url: '../../../pages/index/no_back_tip/no_back_tip?equId=' + data.leaseNoBackInfo.equId + "&positions=" + data.leaseNoBackInfo.positions + "&hospitalName=" + data.leaseNoBackInfo.hospitalName,
          })
        }
      } else {
        leaseShow.resultShow('很抱歉,您有未归还的' + data.tName) // mark: 很抱歉,您有未归还的设备
      }
    } else if (data.rst == 4 || data.rst == 5) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2242')
      that.setData({
        msgRst: 4,
      })
      console.log('data------------------------------------>', data)
      let rentInfo = {};
      rentInfo.backTime = data.backTime;
      rentInfo.borrowTime = data.openTime;
      rentInfo.costTime = data.timeLenStr;
      rentInfo.deposit = data.deposit;
      rentInfo.orderCode = data.orderCode;
      rentInfo.rent = data.rent;
      rentInfo.noPayTitle = data.noPayTitle;
      rentInfo.priceLabel = data.priceLabel;
      rentInfo.orderType = data.orderType;
      rentInfo.inCycleLeaseTimeLen = data.inCycleLeaseTimeLen || '';
      rentInfo.inCycleRecordInfoList = data.inCycleRecordInfoList || [];
      rentInfo.depositBackSuc = data.isAutoRefund;
      wx.navigateTo({
        url: '../../../pages/index/no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
      }) //0718mark--跳转到支付租金页面
    } else if (data.rst == 3) { //未交押金 // mark: 未交押金，可以帮代借
      if (data.isSilenceBack == 1) {
        that.setData({
          isReturn: that.data.isReturn + 1
        })
        leaseShow.backSucShow()
        BLELocker.disconnect('newCon1660')
        that.recordBlueConnectError(ConstantData.err_type.open_lock_slience_back, '静默归还-免押');
        return
      }
      wx.setStorageSync("no_pay_deposit", 1);
      that.setData({
        //设备押金
        equDeposit: data.deposit,
        equId: data.eqId,
        toPayDeposit: !isAllowNoDeposit,
        isPayDeposit: false,
        bindUserType: 0,
        openLockLeaseOptStatus: true,
        rulePic: data.rulePic && data.rulePic.length > 0 ? data.rulePic : null,
        chargeRuleTitle: data.chargeRuleTitle,
        equTypeName: data.tName,
        chargeContent: data.chargeRuleInfo,
        closeTipInfo: data.closeDoorTip,
        mapShowStatus: false,
        bindUserListStatus: false,
        agentLeaseSelStatus: false,
        bindUserList: [],
        wxDeviceId: data.deviceId,
        wxConnType: data.connType,
        wxEqId: data.eqId,
        wxHid: data.hid,
        wxEqTid: data.eqTid,
        serviceUuid: data.homing_uuid,
        homingFEC7: data.homing_FEC7,
        homingFEC8: data.homing_FEC8,
        homingFEC9: data.homing_FEC9,
        ruleList: data.ruleList,
        ruleDesc: data.ruleDesc,
        leaseMaxPriceStr: data.leaseMaxFeeStr,
        isReturn: data.isSilenceBack == 1
      })
      console.log('that.data.isPayDeposit--->>', that.data.isPayDeposit)
      //未交押金
      toPayOrAuthScore()
    } else if (data.rst == -102) {
      errType = ConstantData.err_type.open_lock_102;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2289')
      var desc = data.errInfo ? data.errInfo : "设备维护中,请换其它桩租赁";
      if (desc == '已经关门,请在营业时间使用') {

      }
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc_mini: "L" + data.eqId + "维护中" + errType,
          desc: desc,
          confirm: true,
          desc_center: true
        }
      })

      that.recordBlueConnectError(errType, "开锁:设备维护中,请扫描其他设备,-102")

    } else if (data.rst == -104) {
      errType = ConstantData.err_type.open_lock_104;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2300')
      bleFailShow.modalMsgShow()

      that.setData({
        modal: {
          modal_show: true,
          desc: "很抱歉,非法设备(" + (that.data.rfId ? that.data.rfId : '') + ")无法处理" + errType,
          confirm: true,
          desc_center: true
        }
      })

      that.recordBlueConnectError(errType, "开锁:很抱歉,非法设备无法处理,-104")

    } else if (data.rst == -137) {
      let user_no_back = wx.getStorageSync('user_no_back');
      let errType = '';
      if (user_no_back) {
        if (that.data.switchStatus == 0) {
          let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1
          wx.setStorageSync('insert_fail_time', insert_fail_time + 1)
          if (that.data.no_eject_back_flg == 2) {
            insert_fail_time = 5;
          }

          bleFailShow.modalMsgShow()
          //第3次
          if (insert_fail_time > 2) {
            errType = ConstantData.err_type.open_lock_137_insert_back_times;
            that.setData({
              modal: {
                desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还。",
                desc_mini: "inSwitch " + pile_id + "-" + errType,
                modal_show: true,
                contact: true
              }
            })
          } else {
            errType = ConstantData.err_type.open_lock_137_insert_back;
            that.setData({
              modal: {
                desc: "1、请检查设备是不是已经锁好。\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。",
                desc_mini: "inSwitch " + pile_id + "-" + errType,
                desc_center: false,
                modal_show: true,
                img2_show: true,
                retry95: true,
              }
            })
          }

        } else if (that.data.hookStatus == 1) {
          //轮椅未锁好
          // if(that.data.lockType){
          //   that.setData({
          //     show_lockType:true
          //   })
          // }
          that.data.no_eject_back_flg = data.no_eject_back_flg ? data.no_eject_back_flg : '';
          if (that.data.no_eject_back_flg == 1) {
            //如果是同一用户同一桩位同一轮椅，且三分钟之内，则显示未弹出弹框，给用户再发一次85的机会
            errType = ConstantData.err_type.open_lock_137_hook_noeject_inner;
            console.warn('--三分钟之内，显示未弹出弹框');
            bleFailShow.openFailTipShow(errType)
            that.recordBlueConnectError(errType, '锁钩开关故障归还失败，三分钟之内，显示“未弹出弹框”');
            return;
          } else if (that.data.no_eject_back_flg == 2) {
            //如果是同一用户同一桩位同一轮椅，且三分钟之后，则直接提示联系客服进行归还
            errType = ConstantData.err_type.open_lock_137_hook_noeject_out;
            console.warn('--三分钟之后，提示联系客服');

            bleFailShow.modalMsgShow()

            that.setData({
              openning_show: false,
              loading_show: false,
              modal: {
                modal_show: true,
                desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还",
                desc_mini: "hookSwitch " + pile_id + "-" + errType,
                contact: true
              },
            })
            that.recordBlueConnectError(errType, '锁钩开关故障归还失败，三分钟之后，显示“联系客服归还”');
            return;
          }

          let hook_fail_time = wx.getStorageSync('hook_fail_time') || 1
          wx.setStorageSync('hook_fail_time', hook_fail_time + 1)

          bleFailShow.modalMsgShow()

          if (hook_fail_time > 2) {
            //第3次
            errType = ConstantData.err_type.open_lock_137_hook_back_times;

            that.setData({
              modal: {
                modal_show: true,
                desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还",
                desc_mini: "hookSwitch " + pile_id + "-" + errType,
                contact: true,
              }
            })
          } else {
            errType = ConstantData.err_type.open_lock_137_hook_back;

            that.setData({
              modal: {
                desc: "请将轮椅摆正，将轮椅往里推一推，再左右摇晃轮椅。完成上述操作后点击重试。",
                desc_mini: "hookSwitch " + pile_id + "-" + errType,
                modal_show: true,
                img3_show: true,
                retry95: true,
              }
            })
          }

        } else {
          errType = ConstantData.err_type.open_lock_137_else;
          bleFailShow.modalMsgShow()
          that.setData({
            modal: {
              modal_show: true,
              desc: data.errInfo ? data.errInfo : '归还失败',
              desc_mini: pile_id + '-' + errType,
              desc_center: false,
              confirm: true,
            }
          })
          wx.removeStorageSync('insert_fail_time')
          wx.removeStorageSync('hook_fail_time')
        }
      } else {
        if (that.data.switchStatus == 0) {
          // if(that.data.lockType){
          //   that.setData({
          //     show_lockType:true
          //   })
          // }
          let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1
          wx.setStorageSync('insert_fail_time', insert_fail_time + 1)
          bleFailShow.modalMsgShow()
          //第3次
          if (insert_fail_time > 2) {
            errType = ConstantData.err_type.open_lock_137_insert_rent_times;
            let desc = that.data.connectType && that.data.connectType == '归还' ? '请换一个设备归还，如果取不出来，请联系客服' : '请换一个设备租赁';
            that.setData({
              modal: {
                desc: desc,
                desc_mini: "inSwitch " + pile_id + "-" + errType,
                modal_show: true,
                contact: true,
              }
            })
          } else {
            errType = ConstantData.err_type.open_lock_137_insert_rent;

            that.setData({
              modal: {
                desc: "1、请检查设备是不是已经锁好。\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。",
                desc_mini: "inSwitch " + pile_id + "-" + errType,
                desc_center: false,
                modal_show: true,
                img2_show: true,
                retry95: true,
              }
            })
          }


        } else if (that.data.hookStatus == 1) {
          //轮椅未锁好
          let hook_fail_time = wx.getStorageSync('hook_fail_time') || 1
          wx.setStorageSync('hook_fail_time', hook_fail_time + 1)
          if (that.data.no_eject_back_flg == 2) {
            hook_fail_time = 5;
          }
          bleFailShow.modalMsgShow()
          if (hook_fail_time > 2) {
            //第3次
            errType = ConstantData.err_type.open_lock_137_hook_rent_times;
            let desc = that.data.connectType && that.data.connectType == '归还' ? '请换一个桩归还，如果取不出来，请联系客服' : '请换一个设备租赁';
            that.setData({
              modal: {
                modal_show: true,
                desc: desc,
                desc_mini: "hookSwitch " + pile_id + "-" + errType,
                contact: true
              }
            })
          } else {
            errType = ConstantData.err_type.open_lock_137_hook_rent;
            that.setData({
              modal: {
                desc: "请将轮椅摆正，将轮椅往里推一推，再左右摇晃轮椅。完成上述操作后点击重试。",
                desc_mini: "hookSwitch " + pile_id + "-" + errType,
                modal_show: true,
                img3_show: true,
                retry95: true,
              }
            })
          }
        } else {
          errType = ConstantData.err_type.open_lock_137_else_rent;
          bleFailShow.modalMsgShow()

          that.setData({
            modal: {
              modal_show: true,
              desc: data.errInfo ? data.errInfo : '租借失败',
              desc_mini: pile_id + '-' + errType,
              desc_center: false,
              confirm: true,
            }
          })
          wx.removeStorageSync('insert_fail_time')
          wx.removeStorageSync('hook_fail_time')
        }
      }
      that.recordBlueConnectError(errType, "开锁:" + that.data.isBackChairStatus + "," + data.rst)
    } else if (data.rst == 20) {
      //归还成功后断开蓝牙 // mark: 帮扫码归还处理提示
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2564');
      //代归还成功            
      leaseShow.helpBackSucShow()
      that.recordBlueConnectError(ConstantData.err_type.open_lock_help_back, '帮归还成功');

    } else if (data.rst == 21) {
      //点击归还扫码按钮,未绑定手机号
      wx.showModal({
        title: '温馨提示',
        content: '未绑定手机号,请先登录',
        success(res) {
          if (res.confirm) {
            //去登录页面
            wx.navigateTo({
              url: '../../../pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })



    } else {
      errType = ConstantData.err_type.open_lock_else;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2366');
      var desc = data.errInfo ? data.errInfo : "请扫码重试";
      leaseShow.resultShow(desc + errType)
      that.recordBlueConnectError(errType, "开锁:" + desc + "," + data.rst)
    }
  }
}

//支付押金或授权免押
function toPayOrAuthScore() {
  let that = app.globalData.newConThat
  if (that.data.clickLeaseBtn == 'nodeposit') {
    that.data.isAllowNoDeposit = true
    leaseEquipment()
    return
  }
  if (that.data.clickLeaseBtn == 'deposit') {
    that.data.isAllowNoDeposit = false
    toPayDeposit()
    return
  }
  console.log('支付压面或授权免押--->', that.data.isWorker)
  if (that.data.isWorker == 1) {
    leaseShow.chargeRuleShow()
    return
  }

}

//去支付押金 
function toPayDeposit() {
  var that = app.globalData.newConThat

  if (!that.data.read) {
    wx.showToast({
      title: '请勾选我已阅读'
    })
    return
  }
  if (!that.data.payDepositBtnStatus) {
    return;
  }
  console.log("去支付。。。equTid=", that.data.equId)

  that.data.payDepositBtnStatus = false

  app.executeRequest(function (header) {

    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/to_pay',
      method: 'post',
      header: header,
      data: {
        eqId: that.data.equId,
        mac: that.data.conMac
      },
      success: function (res) {
        console.log('/lease_dposit/wxmini/to_pay----->', res)
        let netErr = app.handleRes(res, that);
        if (netErr) {
          return
        }
        var data = res.data
        if (data.result == 0) {
          connectShow.clickLeaseFirstShow()
          toPay(data.data)
        } else if (data.result == -1) {
          wx.navigateTo({
            url: '/pages/user_record/deposit/user_deposit',
          })
        } else {
          that.setData({ // mark: 弹框去缴纳押金
            alertBoxStatus: true,
            alertBoxTipContent: data.description,
            payDepositBtnStatus: true,
            payDepositBtnTxt: "去缴纳"
          })
        }

      },
      fail: function () {
        that.setData({
          payDepositBtnStatus: true,
          payDepositBtnTxt: "去缴纳"
        })
      }
    })

  })
}


function toPay(orderCode) {
  var that = app.globalData.newConThat
  console.log("去支付。。。" + orderCode);

  app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
        method: 'post',
        header: header,
        data: {
          orderCode: orderCode,
          loginCode: loginCode,
          wxErr: err
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          var data = res.data
          console.log("支付结果---" + data.result)
          if (data.result != 0 || !data.data || !data.data.timeStamp) {
            leaseShow.resultShow(data.description ? data.description : '押金支付失败')
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_fail, '押金支付请求失败')
            return
          }

          app.globalData.isOpenLock = true;
          that.setData({
            hideIsDisconnectStat: false, //支付成功后隐藏不关闭蓝牙
            openning_show: true, //200114 冯慧敏，押金支付之前就显示开锁中，以防止押金支付成功后用户有机会再次点击扫码，影响开锁
            openning_desc: '正在支付押金...',
          })

          if (that.data.checkPayStatusInterval) {
            clearInterval(that.data.checkPayStatusInterval);
          }
          that.data.isPayDepositSuccess = false;
          that.data.checkPayStatusInterval = setInterval(() => {
            console.log('【轮询押金支付状态】');
            if (that.data.isPayDepositSuccess) {
              clearInterval(that.data.checkPayStatusInterval);
              that.data.checkPayStatusInterval = null
              return;
            }

            noDepositLease.queryPayDepositStatus(orderCode).then(res => {
              console.log('【押金支付状态查询】已支付...' + res);
              that.data.isPayDepositSuccess = true;
              payDepositSuccess();
              clearInterval(that.data.checkPayStatusInterval)
            }).catch(error => {
              console.log('【押金支付状态查询】未支付...' + error);
            })

          }, 1000);

          wx.requestPayment({
            appId: 'wx0e458dc331e557cc',
            timeStamp: data.data.timeStamp,
            nonceStr: data.data.nonceStr,
            package: data.data.package,
            signType: data.data.signType,
            paySign: data.data.paySign,
            success: function (res) {
              if (that.data.isPayDepositSuccess) {
                that.getSubscribeMessage('押金支付成功', null);
                return;
              }
              payDepositSuccess();
            },
            fail: function (res) {
              app.globalData.isOpenLock = false;
              that.recordBlueConnectError(ConstantData.err_type.deposit_pay_cancel, "押金FAIL:" + JSON.stringify(res))
              common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'index2-' + JSON.stringify(res) : '');
              if (that.data.checkPayStatusInterval) {
                clearInterval(that.data.checkPayStatusInterval);
              }
            },
            complete: function (res) {
              console.log("complete--" + data.data.paySign)
              console.log(res)
              that.data.payDepositBtnStatus = true
            }
          })


        }
      })

    })

  });

}

function payDepositSuccess() {
  var that = app.globalData.newConThat

  if (that.data.checkPayStatusInterval) {
    clearInterval(that.data.checkPayStatusInterval);
  }
  that.setData({
    checkPayStatusInterval: null,
  });

  that.recordBlueConnectError(ConstantData.err_type.deposit_pay_confirm, "[押金]支付成功")
  that.getSubscribeMessage('押金支付成功', function () {
    connectShow.payDepositOpenShow()
    wx.setStorageSync("no_pay_deposit", 0);
    that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success, '押金支付成功,准备开锁...');
    if (that.data.noDepositFail) {
      that.setData({
        noDepositFail: false
      })
    }

    if (that.data.isColonyCon) {
      //网关开锁前标记，在断开连接时进行判断是否
      app.globalData.gatewayUnlockFlg = true;
      //网关开锁前标记的时间点，判断断开时校验时间，如果超过30秒，则认为标记失效进行断开
      app.globalData.gatewayUnlockFlgTime = new Date().getTime();
      that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]gateway开始直接开锁-押金支付成功");
      leaseEquipment(true);
      return;
    }

    //判断是否还在连接，连接着的直接开锁进行租赁
    wx.getConnectedBluetoothDevices({
      services: ['FEE7'],
      success: function (res) {
        console.log("111----current connected blue " + JSON.stringify(res))
        if (res.devices && res.devices.length > 0) {
          //展示收费规则提示框
          that.setData({
            payDepositStat: true,
            showModalStatus: false,
            mapShowStatus: false,
            hideIsDisconnectStat: false,
            bindUserListStatus: false,
            agentLeaseSelStatus: false,
            isPayDeposit: true
          })
          that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]开始直接开锁-押金支付成功");
          leaseEquipment(true);
        } else {
          that.data.bleDepositPaySuc = true;
          that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_connect, "[连接]没有设备,重新连接-押金支付成功")
          connectCurrentBlue(that)
        }
      },
      fail: function () {
        that.data.bleDepositPaySuc = true;
        that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_reconnect, "[连接]获取失败,重新连接-押金支付成功")
        connectCurrentBlue(that)
      }
    })
  });
}


//开锁并租赁设备
function leaseEquipment(isRedirectOpenLock) {

  var that = app.globalData.newConThat
  console.log("代租赁-----uid=" + that.data.selBindUserId)

  var systemInfo = wx.getStorageSync('systeminfo');
  console.log("----->systeInfo=", systemInfo);
  var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
  console.log("----->isCouldNoDeposit=", isCouldNoDeposit, that.data.isAllowNoDeposit);

  app.executeRequest(function (header) {
    console.log('header', header);
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/equipment_order',
      method: 'post',
      header: header,
      data: {
        eqid: that.data.wxEqId,
        hid: that.data.wxHid,
        eqtid: that.data.wxEqTid,
        bindUid: that.data.selBindUserId,
        bindUserType: that.data.bindUserType,
        isOldReq: 'lease_order', //2019-07-23用于兼容之前版本订单不能进行隐藏
        miniNoDeposit: isCouldNoDeposit && that.data.isAllowNoDeposit && !that.data.noDepositFail, //系统支持免押并且可以用户可以免押并且用户没有取消免押
        isGateway: that.data.isColonyCon //是否为网关下单,true是，false否
      },
      success: function (res) {
        let netErr = app.handleRes(res, that);
        if (netErr) {
          that.setData({
            openning_show: false,
          })
          return
        }
        that.data.send85Time = new Date().getTime();
        console.log('---租赁请求成功:', res)
        that.recordBlueConnectError(ConstantData.err_type.deposit_created_order, "生成记录-" + that.data.rfId + ",rst=" + res.data.result)
        that.setData({
          hasOrderFlg: true,
          openning_show: true,
          openLockLeaseOptStatus: true,
          equId: res.data.data ? res.data.data.equId : 0,
          opentime: res.data.data ? res.data.data.openTime : '',
          orderCode: res.data.data ? res.data.data.orderCode : '',
        })
        wx.setStorageSync('opentime', res.data.data ? res.data.data.openTime : '');
        wx.setStorageSync('equId', res.data.data ? res.data.data.equId : 0);
        var result = res.data.result;
        if (result == 0) {

          if (res.data.err === "no_pay_deposit") {
            //未交押金
            wx.showModal({
              title: '温馨提示',
              content: '尚未支付押金，请重新扫码支付，谢谢!',
              showCancel: false,
              complete: (res) => {}
            })
            return;
          }

          console.log("租赁成功");
          if (isRedirectOpenLock === true) {
            console.log("租赁成功,直接开锁");
            that.setData({
              openning_desc: '订单生成,准备开锁...',
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_send85, "直接开锁-" + that.data.rfId);
            that.send85Command();
            return;
          }
          var backData = res.data.data;
          if (backData == null) {
            wx.showToast({
              title: '订单已成功',
            })
            that.recordBlueConnectError(ConstantData.err_type.lease_order_repeat, '此设备订单已生成')
            return
          }
          if (that.data.isAllowNoDeposit) {
            wx.setStorageSync("outOrderCode", backData.outOrderCode);
            if (!backData.no_deposit_info) {
              //免押创建订单失败,取消免押的订单，走押金支付
              noDepositLease.noSureCancelOrder(that);
              //免押失败使用交押金租赁
              that.setData({
                callServiceBoxStatus: true,
                openLockLeaseOptStatus: true,
                openning_show: false,
                showModalStatus: false,
                loading_show: false,
                bindUserListStatus: false,
                payDepositStat: false,
                agentLeaseSelStatus: false
              });
              return;
            }
            //免押跳转开锁中
            app.globalData.isOpenLock = true;
            console.log("开启免押跳转--->true")
            //隐藏不断开蓝牙
            that.setData({
              hideIsDisconnectStat: false,
              noDepositBackFlg: false,
              openning_desc: '免押授权,页面跳转中(15秒)...',
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_to_auth, '免押授权,页面跳转中...')

            if (that.data.pt == 'noback') {
              //2019-07-25从使用中的页面扫码进行免押租赁的需要清除pt的标记值，以便免押流程进行
              that.data.pt = '';
            }

            that.data.noDepositCount = 15;
            app.globalData.noDepositTimer = setInterval(() => {
              that.data.noDepositCount = that.data.noDepositCount - 1;
              if (that.data.noDepositCount <= 0) {
                clearTimeout(app.globalData.noDepositTimer);
                that.setData({
                  openning_show: false,
                  callServiceBoxStatus: true,
                  hospitalTipBox: false,
                  toPayDeposit: false,

                  hideIsDisconnectStat: true,
                  noDepositBackFlg: true,
                })
              } else {
                that.setData({
                  openning_desc: '免押授权,页面跳转中(' + that.data.noDepositCount + '秒)...',
                })
              }
            }, 1000)

            noDepositLease.toWxNoDepositLeasePage(backData.no_deposit_info, backData.outOrderCode, that);
          } else {
            that.send85Command();
          }
        } else {
          console.log("租赁失败")
          that.setData({
            openning_show: false,
          })
          if ('参数有误1' == res.data.description) {
            //存在未支付订单
            wx.showModal({
              title: '温馨提示',
              confirmText: "去支付",
              content: '存在未支付订单',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/user_record/lease/user_lease',
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })

            return;
          }

          if (result == 6000) {
            leaseShow.resultShow('如果确认再次租借')
            return;
          }

          leaseShow.resultShow('租赁失败！' + result + 'Z' + that.data.wxHid)

        }
      },
      fail: function (res) {
        that.recordBlueConnectError(ConstantData.err_type.deposit_created_fail, "生成记录fail-" + that.data.rfId + ';res:' + JSON.stringify(res))

        console.log("租赁失败", res)
        leaseShow.resultShow('服务器忙,请重新扫码 Z' + that.data.wxHid)

      },
      complete: function () {}
    })
  })


}

function connectCurrentBlue(that) {
  console.log("开始蓝牙连接：", that.data.curBlueName)
  //隐藏可以关闭蓝牙
  that.data.hideIsDisconnectStat = true;
  if (that.data.curBlueName) {
    connectShow.reday()
    connectBLEDevice(that.data.curBlueName)
  } else {
    leaseShow.resultShow('请重新扫码!')
  }
}


function getDevIdAndConnect(qrc) {
  if (app.globalData.timeoutConnectTimeout) {
    clearTimeout(app.globalData.timeoutConnectTimeout)
  }

  var that = app.globalData.newConThat;
  that.handleStatus = (status, data) => {
    handleStatus(status, data)
  }
  var systemInfo = that.data.systemInfo
  connectShow = that.data.connectShow
  leaseShow = that.data.leaseShow
  bleAuthShow = that.data.bleAuthShow
  bleFailShow = that.data.bleFailShow
  app.globalData.devConnected = false

  connectShow.reday()
  //请求获取设备mac
  app.globalData.beforeConIsGateway = false;

  console.log("-----*****************----qrc=" + qrc)
  that.data.scanningCode = false;
  //初始扫码95重试标记清空
  that.data.retry95Flg = false;
  that.data.canRetry85 = false;
  that.data.canceledConnect = false;
  if (systemInfo && ((systemInfo.model && systemInfo.model.toLowerCase().indexOf('iphone') != -1) || (systemInfo.brand && systemInfo.brand.toLowerCase().indexOf('iphone') != -1)) && systemInfo.system.toLowerCase().indexOf('ios') < 0) {
    systemInfo.system = 'ios' + systemInfo.system;
  }
  var phoneModel = systemInfo ? systemInfo.model : "";
  var phoneType = systemInfo ? systemInfo.brand : "";
  app.globalData.disconnectLineNum = '';
  that.data.reqConDevTime = null;
  app.executeRequest(function (header) {
    console.log('now request device')
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/connect/device',
      method: 'post',
      header: header,
      data: {
        qrc: qrc,
        system: systemInfo.system,
        phoneModel: phoneType, //手机厂商
        phoneType: phoneModel, //手机型号
        isScanBack: that.data.isScanBack,
        lng: that.data.locationLng,
        lat: that.data.locationLat,
        locTime: that.data.locationTime,
      },
      success: function (res) {
        let netErr = app.handleRes(res, that);
        if (netErr) {
          return
        }
        //校验服务器
        if (!that.data.reqConDevTime) {
          that.data.reqConDevTime = new Date().getTime()
        } else {
          let diff = new Date().getTime() - that.data.reqConDevTime
          if (diff < 5000) {
            console.log('服务返回两次getDev-->', res)
            return
          }
        }
        console.warn("getDev--=====res=", res);
        that.data.qrc = qrc;
        //用于one more陪护椅的开锁状态赋值
        app.globalData.curConMac = that.data.conMac;
        that.data.conDevRes = res
        if (res.data.rst == 10) {
          //用户刚刚租借成功提示,防止用户误操作再次租借            
          common.clearConTimeCountTimer(1522)
          let extP = res.data.extParams
          that.setData({
            beforeLeaseTipTitle: extP && extP.beforeLeaseTipTitle ? extP.beforeLeaseTipTitle : that.data.beforeLeaseTipTitle,
            beforeLeaseTipContent: extP && extP.beforeLeaseTipContent ? extP.beforeLeaseTipContent : that.data.beforeLeaseTipContent,
            beforeLeaseIsContinue: extP && extP.beforeLeaseIsContinue ? extP.beforeLeaseIsContinue : true,
          })
          leaseShow.backSucToLeaseTip()
          return
        }
        if (res.data.rst == 10001) {
          bleFailShow.modalMsgShow()
          let desc = res.data.desc
          console.log('desc======>', desc)
          that.data.scanningCode = false;
          that.setData({
            loading_show: false,
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_net_rst_err, 'modalErr--qrc=' + qrc + ';res:' + JSON.stringify(res));
          wx.reLaunch({
            url: '../../../pages/index/index?desc=' + desc,
          })
          return
        }

        let isOk = res.data.rst === 0;
        if (!isOk) {
          bleFailShow.modalMsgShow()
          that.data.scanningCode = false;
          let descInfo = res.data.desc ? res.data.desc : '错误编号' + res.data.rst;
          that.setData({
            loading_show: false,
            modal: {
              modal_show: true,
              desc: descInfo,
              confirm: true
            }
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_net_rst_err, 'modalErr--qrc=' + qrc + ';res:' + JSON.stringify(res));
          return;
        }

        //处理返回数据并调用
        handleConDevRes()

      },
      fail: function (res) {
        console.log("根据qrc获取mac名称请求失败", res)
        that.data.scanningCode = false;
        let netErr = app.handleRes(res, that);
        if (netErr) {
          return
        }
        bleFailShow.modalMsgShow()
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '请重新扫码-' + ConstantData.err_type.qrc_mac_fail,
            confirm: true
          }
        })
        that.recordBlueConnectError(ConstantData.err_type.qrc_mac_fail, 'modalErr--qrc=' + qrc + ';res:' + JSON.stringify(res));
      }
    })

  })

}

/**
 * 处理扫码从服务获取设备信息
 */
function handleConDevRes() {
  let that = app.globalData.newConThat
  let res = that.data.conDevRes
  console.log("处理扫码获取的设备信息:", res)
  if (res.data.extParams && res.data.extParams.lockType) {
    that.setData({
      lockType: res.data.extParams.lockType
    })
  }
  that.recordBlueConnectError(ConstantData.err_type.qrc_mac_suc, 'getDevIdAndConnect macId=' + (res.data ? res.data.macId : 'null'));
  //扫码后获取到的连接的mac地址
  that.data.conMac = res.data ? res.data.macId : "";
  that.data.conBlueName = res.data ? res.data.extParams.blueName : "";
  app.globalData.conBlueVer = res.data ? res.data.extParams.blueVer : "";

  startConnect(res);
}

//开始进行蓝牙连接
function startConnect(res) {
  var that = app.globalData.newConThat;
  //取消重试
  let netErr = app.handleRes(res, that);
  if (netErr) {
    that.data.scanningCode = false;
    that.setData({
      loading_show: false
    })
    return
  }
  if (res.data.isBindPhone == 0) {
    that.setData({
      phoneAuthStatus: true,
      phoneAuthBtt: 'scan',
      loading_show: false
    });
    wx.showToast({
      title: '请先登录',
      icon: 'none'
    })
    that.data.scanningCode = false;
    return;
  }
  that.setData({
    phoneAuthStatus: false,
    phoneAuthBtt: ''
  });
  app.globalData.curConHid = null;
  if (res.data.hid) {
    that.setData({
      pile_id: res.data.hid
    })
    app.globalData.curConHid = res.data.hid;
    wx.setStorageSync('pileId', res.data.hid);
    that.data.pile_type = res.data.hpVer && res.data.hpVer.indexOf('长') != -1;
  }
  app.globalData.isLeaseCon = false;
  app.globalData.isAllowUpgrade = false;
  app.globalData.isBeforeLeaseUpgrade = false;
  app.globalData.allowUpgradeOtherMac = false;
  app.globalData.isPayUpgrade = false;
  app.globalData.isLockUpgrade = false;
  app.globalData.otherMacs = [];
  that.data.isSend98Cmd = false;
  that.data.canRetry85 = false;

  if (res.data.extParams) {
    that.data.conDevExtParams = res.data.extParams;
    app.globalData.isAllowUpgrade = res.data.extParams.isAllowUpgrade;
    app.globalData.lastDriveVer = res.data.extParams.lastDriveVer;
    app.globalData.isBeforeLeaseUpgrade = res.data.extParams.isBeforeLeaseUpgrade;
    app.globalData.isPayUpgrade = res.data.extParams.isPayUpgrade;
    app.globalData.isLockUpgrade = res.data.extParams.isLockUpgrade;
    app.globalData.allowUpgradeOtherMac = res.data.extParams.allowUpgradeOtherMac ? res.data.extParams.allowUpgradeOtherMac : false;
    app.globalData.otherMacs = res.data.extParams.otherMacs ? res.data.extParams.otherMacs : [];
    //是否发送98命令
    that.data.isSend98Cmd = res.data.extParams.isSend98Cmd ? res.data.extParams.isSend98Cmd : false;
    //网关连接超时的时长。默认20秒超时
    app.globalData.gatewayConTimeout = res.data.extParams.gatewayConTimeout ? res.data.extParams.gatewayConTimeout : 20000;
    //网关开锁超时的时长,默认15秒超时
    app.globalData.gatewayUnlockTimeout = res.data.extParams.gatewayUnlockTimeout ? res.data.extParams.gatewayUnlockTimeout : 15000;
    //网关连接失败后多长时间内使用蓝牙重试连接，默认为5分钟内再次扫码可使用蓝牙连接
    app.globalData.gatewayFailBleConTime = res.data.extParams.gatewayFailBleConTime ? res.data.extParams.gatewayFailBleConTime : 30000;
    //蓝牙连接失败后多长时间内使用网关重试连接，默认为5分钟内再次扫码可使用网关连接
    app.globalData.gatewayBleFailConTime = res.data.extParams.gatewayBleFailConTime ? res.data.extParams.gatewayBleFailConTime : 30000;
  }

  //清空定时器
  app.clearTimeoutTimer();
  //清空秘钥
  that.data.blepwd = '';

  app.globalData.startConTime = new Date().getTime();
  that.data.newConFlg = res.data.newConFlg;

  //连接的调用不允许进行升级的操作
  app.globalData.isBeforeLeaseUpgrade = false;
  app.globalData.isLeaseCon = true;
  //扫完码拿到数据执行连接的过程
  executeConnect(res);
}

//执行蓝牙连接
function executeConnect(res) {
  var that = app.globalData.newConThat;
  //清空选择的设备类型
  that.setData({
    selTypeList: [],
  })
  //连接前去除95重试标记
  that.data.retry95Flg = false;
  let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
  let errType = '';
  let user_no_back = wx.getStorageSync('user_no_back');
  if (res.data.rst == 0 || (res.data.rst == 6 && user_no_back)) {
    var hpStat = res.data.hpStat;
    if (hpStat && hpStat != 0 && hpStat != 1) {
      // var desc = res.data.desc ? res.data.desc : "维护中,请使用其他设备";
      if (user_no_back) {
        errType = ConstantData.err_type.qrc_maintain_back;
        var desc = "归位桩维护中,如您确定设备已锁在桩上拉不下来,请联系客服处理";
        var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
        var contact = true;
        var confirm = false;
      } else {
        errType = ConstantData.err_type.qrc_maintain_rent;
        var desc = res.data.desc ? res.data.desc : "归位桩维护中,请换其它桩租赁";
        var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
        var contact = false
        var confirm = true
      }
      bleFailShow.modalMsgShow()
      //归位桩存在问题
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: desc,
          desc_mini: desc_mini,
          open_location_show: false,
          retryConnect: false,
          retry95: false,
          confirm: confirm,
          contact: contact
        }
      })
      that.recordBlueConnectError(errType, 'modalErr:归还失败');
      that.data.scanningCode = false;
      return;
    }

    var name = res.data.macId;
    if (name == null || name == '') {
      console.log("根据qrc获取mac名称为空")
      errType = ConstantData.err_type.qrc_mac_null;
      bleFailShow.modalMsgShow()
      that.setData({
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '请重新扫码-' + errType,
          confirm: true
        }
      })
      that.recordBlueConnectError(errType, 'modalErr:获取mac为空');
      that.data.scanningCode = false;
      return
    }
    var deviceId = res.data.deviceId

    let isExtBlueName = that.data.conBlueName && that.data.conBlueName.indexOf("DK") == -1;
    let conBlueName = isExtBlueName ? that.data.conBlueName : "DK" + name;
    that.setData({
      loading_show: true,
      loading_desc: '开始连接...',
      agentLeaseSelStatus: false,
      showModalStatus: false,
      wxDeviceId: deviceId, //数据库存储的公众号获取的设备id
      curBlueName: conBlueName,
      isNoRfidOpen: res.data.isNoRfidOpen,
      isJudgeInsertSwitch: res.data.judgeInsertSwitch,
      isBackChairStatus: res.data.backStat,
      curIsDirectCon: res.data.curIsDirectCon
    })

    setTimeout(function () {
      that.data.scanningCode = false;
    }, 1000);

    app.globalData.isAllowBroadcastBack = res.data.isAllowBroadcastBack;

    //蓝牙集群节点判断处理
    //是否存在蓝牙节点
    var colonyIsExists = res.data.colonyIsExists;
    //集群节点是否在使用中0未占用,1被占用
    var colonyIsUsing = res.data.colonyIsUsing;
    //是否直接使用蓝牙节点连接
    var hpIsColony = res.data.hpIsColony;
    that.data.hpIsColony = hpIsColony;
    //是否可直接使用节点
    var colonyIsDirectUse = hpIsColony == 1 && colonyIsUsing == 0 && colonyIsExists == 1;

    console.log("是否直接网关连接:", colonyIsDirectUse);

    let firstConFail = colonyBlue.isBleFailGatewayCon();
    console.log("是否首次蓝牙连接失败:", firstConFail);
    //是否在连接失败后使用
    var colonyIsFailUse = hpIsColony == 2 && colonyIsUsing == 0 && colonyIsExists == 1;
    if (colonyIsFailUse && firstConFail) {
      colonyIsDirectUse = true;
      that.data.colonyConFail = 0
    }

    that.data.noBackEqId = res.data.extParams.noBackEqId;
    //网关连接失败后5分钟内扫码，改用蓝牙连接
    let isBleCon = colonyBlue.isGatewayFailBleCon();
    console.log("是否首次网关连接失败:", isBleCon,';gatewayFialCount:'+that.data.colonyConFail, ';isDirectGateway:' + colonyIsDirectUse);
    if (!isBleCon && colonyIsDirectUse && that.data.colonyConFail < 3) {
      //开锁前判断是否是蓝牙集群的连接
      that.data.mac = name
      that.data.colonyIsExists = colonyIsExists
      common.storeGatewayClientType();
      console.log("开始直接连接蓝牙集群---->");
      //直接使用蓝牙集群连接
      colonyBlue.connectDev(name, that);
      return;
    }

    if (that.data.pt == 'blue_tip') {
      that.data.pt = '';
    }


    if (!that.validateBleAuth()) {
      //蓝牙未开启，提示用户开启蓝牙
      that.recordBlueConnectError(ConstantData.err_type.deposit_no_ble, '扫码后直接连接前,提示打开蓝牙');
      return
    }

    //非网关的使用wxmini
    common.storeWxClientType(that);
    //进行蓝牙连接
    that.data.timeout95RetryFlg = true; //连接后95超时可以进行一次重连
    that.data.retryCon = false; //刚开始还没有进行重试点击
    connectBLEDevice(conBlueName);
  } else if (res.data.rst == 6) { //共享陪护床
    bleFailShow.modalMsgShow()
    that.setData({
      modal: {
        modal_show: true,
        desc: that.data.conDevExtParams && that.data.conDevExtParams.close_tip ? that.data.conDevExtParams.close_tip : "当前时间不可租借",
        confirm: true
      }
    })
    that.data.scanningCode = false;
  } else {
    errType = ConstantData.err_type.qrc_mac_rst;
    bleFailShow.modalMsgShow()
    that.setData({
      modal: {
        modal_show: true,
        desc: '请重新扫码-' + errType,
        confirm: true
      }
    })
    that.data.scanningCode = false;
    console.log("根据qrc获取mac请求返回值非0：" + res.data.rst)
    that.recordBlueConnectError(errType, 'modalErr--qrc=' + that.data.qrc + '--' + res.data.rst);
  }

}


//开锁
function openLock() { // mark: 免押租借/交押金租借
  var that = app.globalData.newConThat
  let leaseShow = that.data.leaseShow
  that.data.bleDepositPaySuc = false;

  if (that.data.curContIsBle) {
    //判断蓝牙是否连接
    if (!app.globalData.devConnected) {
      leaseShow.resultShow("设备连接已断开，请重新扫码租借!")
      return
    }
  }
  if (!that.data.read) {
    wx.showToast({
      title: '请勾选我已阅读'
    })
    return
  }
  if (that.data.isAllowNoDeposit && !that.data.noDepositFail) {
    //允许免押
  } else if (!that.data.isPayDeposit) {
    //非免押且未支付押金,弹去支付押金的框
    //交押金租赁
    leaseShow.chargeRuleShow()
    return;
  }

  if (that.data.openLockLeaseOptStatus == false) {
    console.log("租赁中")
    wx.showToast({
      title: '租赁中...',
      duration: 2500
    })
    return
  }
  that.setData({
    openning_show: true,
    openning_desc: '开始请求租赁...',
    showModalStatus: false,
    mapShowStatus: true,
    loading_show: false,
    openLockLeaseOptStatus: false,
    bindUserListStatus: false,
    payDepositStat: false
  })

  that.recordBlueConnectError(ConstantData.err_type.deposit_create_order, "用户点击租赁,开始请求租赁-" + that.data.rfId)

  //进行租赁
  leaseEquipment();

}

/**
 * 获取新连接错误标记的错误码
 */
function getTimeoutReasonCode() {
  let errDesc = app.globalData.conErrDesc;
  let errCode = '10030';
  if (errDesc) {
    if (errDesc.indexOf('搜索超时') != -1) {

      errCode = '10034';
    } else if (errDesc.indexOf('openAdapterTimeout') != -1) {
      errCode = '100312';
    } else if (errDesc.indexOf('locationAuthTimeout') != -1) {
      errCode = '100313';
    } else if (errDesc.indexOf('openBluetoothAdapter') != -1) {
      let systemInfo = wx.getStorageSync('systeminfo');
      if (systemInfo.system.toLowerCase().indexOf('ios 13') != -1) {
        errCode = '100310';
      } else {
        errCode = '10031';
      }
    } else if (errDesc.indexOf('getBluetoothDevices') != -1) {
      errCode = '10032';
    } else if (errDesc.indexOf('startBluetoothDevicesDiscovery') != -1) {
      errCode = '10033';
    } else if (errDesc.indexOf('createBLEConnection') != -1) {
      errCode = '10035';
    } else if (errDesc.indexOf('getBLEDeviceServices') != -1) {
      errCode = '10036';
    } else if (errDesc.indexOf('getBLEDeviceCharacteristics') != -1) {
      errCode = '10037';
    } else if (errDesc.indexOf('notifyBLECharacteristicValueChanged') != -1) {
      errCode = '10038';
    } else if (errDesc.indexOf('receivingData') != -1) {
      errCode = '10039';
    }
  }
  return errCode;
}



function getBleDevId(mac) {
  let devId = ''
  for (let i = 0; i < mac.length; i += 2) {
    devId += mac[i] + mac[i + 1] + ':'
  }
  return devId.substring(0, devId.length - 1)
}

module.exports.connectBox = connectBox
exports.getBleDevId = getBleDevId
exports.getDevIdAndConnect = getDevIdAndConnect
exports.openOrReturnEquitment = openOrReturnEquitment
exports.handleStatus = handleStatus
exports.leaseEquipment = leaseEquipment
exports.connectBLEDevice = connectBLEDevice
exports.toPayDeposit = toPayDeposit